// pages/home/subscribe/list/list.js
const app = getApp();
import api from "../../../../common/api"
import * as user from '../../../../models/user'
import * as filter from "../../../../models/filter";
import { dialog } from '../../../../component/userStatusDialog/control'
const cityMap = require('./../../../../utils/city')
import locationBehavior from './../../../../behaviors/location';

Page({
  behaviors: [locationBehavior],

  /**
   * 页面的初始数据
   */
  data: {
    districtOptions: [],
    cityName: '',
    cityCode: '',
    _isRefreshFollow: false,
    hasOfficialAccountStatus: false,
    hasVipStatus: false,
    defaultTabSelect: '',
    tabSelect: '',
    tabList: [{
      id: 'my',
      label: '我的情报',
      add: '',
    }, {
      id: 'sales',
      label: '二手',
      add: '',
    }, {
      id: 'rent',
      label: '出租',
      add: '',
    }],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initData(options)
    this.gioEnter(options)
    app.globalData.loginPromise.then(() => {
      app.mobileLogin(false, '', false)
        .then(() => {
          this.deldeteUnreadMesgCount()

          user.getVip()
            .then(() => {
              this.setData({
                hasVipStatus: true,
              })
            })

          user.getOfficialAccount()
            .then(() => {
              this.setData({
                hasOfficialAccountStatus: true,
              })
            })

          this.getCurrentCity()
            .then(() => {
              this.getBizcircles(this.data.cityCode)
            })

        })
        .catch(() => {
          app.globalData.afterMobileAuthorCallBack = () => {
            wx.redirectTo({
              url: "/pages/home/subscribe/list/list"
            });
          };
        })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideShareMenu()
    this.refreshOfficialAccount()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const {
      tabSelect
    } = this.data
    this.selectComponent(`#list-${tabSelect}`) && this.selectComponent(`#list-${tabSelect}`).onPageReachBottom()
  },

  onPageScroll: function (e) {
    const {
      tabSelect
    } = this.data
    if (tabSelect !== 'my') return
    this.selectComponent(`#list-${tabSelect}`) && this.selectComponent(`#list-${tabSelect}`).onPageScroll(e)
  },

  initData(options) {
    this.setData({
      defaultTabSelect: options.tab || 'my',
      tabSelect: options.tab || 'my',
      filterRange: options.range || '',
      filterType: options.type || ''
    })
  },

  onTabChange(e) {
    const {
      tabSelect
    } = this.data
    let target = e.detail
    if (tabSelect === target) return

    this.setData({
      tabSelect: target,
      filterRange: '',
      filterType: '',
    })
  },

  onClickSubscribe() {
    let t = this
    this.checkOfficialAccount()
      .then(() => {
        wx.navigateTo({
          url: '/pages/home/subscribe/select/select',
        })
      })
      .catch(() => {
        dialog({
          dialog: 'public1',
          confirm: () => {
            this.data._isRefreshFollow = true
            let url = 'https://mp.weixin.qq.com/s/I8sdEESdeHIoKLyYVnDcYQ'
            wx.navigateTo({
              url: `/pages/webView/webView?webViewUrl=${url}`
            })
          },
          cancel: () => {
            wx.showModal({
              title: '',
              content: '只差一步，开启树懒房源情报全部功能',
              confirmText: '去完成',
              cancelText: '残忍放弃',
              confirmColor: '#F75352',
              success(res) {
                if (res.confirm) {
                  t.data._isRefreshFollow = true
                  let url = 'https://mp.weixin.qq.com/s/I8sdEESdeHIoKLyYVnDcYQ'
                  wx.navigateTo({
                    url: `/pages/webView/webView?webViewUrl=${url}`
                  })
                }
              }
            })
          }
        })
      })
  },

  checkOfficialAccount() {
    return new Promise((resolve, reject) => {
      user.getOfficialAccount()
        .then(res => {
          if (res === '1') {
            resolve()
          } else {
            reject()
          }
        })
        .catch(() => {
          wx.showToast({
            icon: 'none',
            title: '网络错误，请稍后再试~',
          })
        })
    })
  },

  refreshOfficialAccount() {
    if (this.data._isRefreshFollow) {
      this.data._isRefreshFollow = false
      user.updateOfficialAccount()
    }
  },
 
  // 清楚未读房源情报
  deldeteUnreadMesgCount() {
    return new Promise((resolve, reject) => {
      api.deldeteUnreadMesgCount({}, (res) => {
        if (res && res.data && res.data.isSuccess) {
          resolve()
        } else {
          reject()
        }
      })
    })
  },

  getCurrentCity() {
    return new Promise((resolve, reject) => {
      this.getCityBe(true)
        .then((city) => {
          let cityCode = ''
          cityMap.cityObjs.forEach(item => {
            if (item.city === city) {
              cityCode = item.code || ''
            }
          })
          if (cityCode) {
            this.setData({
              cityName: city,
              cityCode: cityCode,
            });
          } else {
            this.setData({
              cityName: '上海市',
              cityCode: '310000',
            });
          }
          resolve()
        })
        .catch(() => {
          this.setData({
            cityName: '上海市',
            cityCode: '310000',
          });
          resolve()
        })
    })
  },

  getBizcircles(cityCode = '') {
    return new Promise((resolve, reject) => {
      api.getBizcircles({
        cityCode
      }, (res) => {
        if (res && res.data && res.data.content && res.data.content.length) {
          this.setData({
            districtOptions: filter.formatDistrictOptions(res.data.content)
          })
          resolve()
        } else {
          reject()
        }
      })
    })
  },

  // formatDistrictOptions(options) {
  //   if (!(options && options.length)) {
  //     return []
  //   }
  //   let list = options.map(item => {
  //     const list = {
  //       value: item.areaCode,
  //       label: item.areaName,
  //     }
  //     if (item.hdBizcircleList) {
  //       list.children = item.hdBizcircleList.map(itx => {
  //         return {
  //           value: itx.id,
  //           label: itx.bizcircleName,
  //         }
  //       })
  //     } else {
  //       list.children = []
  //     }
  //     return list
  //   })

  //   return [{
  //     value: 'area',
  //     label: '区域',
  //     children: list
  //   }]
  // },

  gioEnter(options) {
    if ((wx.getLaunchOptionsSync() || {}).scene === 1043 && options.from === 'push') {
      wx.gio("track", 'fromOfficialAccount', {
        'subscribe_type': options.type
      });
    }
  }

})